<template>
  <!--表单组件-->
  <div>
    <vue-context-menu
      :context-menu-data="leftContextMenuData"
      @tableConfig="leftTableConfig"
    />
    <vue-context-menu
      :context-menu-data="rightContextMenuData"
      @tableConfig="rightTableConfig"
    />
    <!-- 表格配置 -->
    <el-dialog
      title="表格配置"
      :visible.sync="leftTableConfigShow"
      append-to-body
      width="60%"
    >
      <j-table-column-config :columns.sync="leftList" @tabSave="leftTabSave" @pit="pit"/>
    </el-dialog>

    <el-dialog
      title="表格配置"
      :visible.sync="rightTableConfigShow"
      append-to-body
      width="60%"
    >
      <j-table-column-config :columns.sync="rightList" @tabSave="rightTabSave" @pit="pit"/>

    </el-dialog>
    <el-row :gutter="10">
      <el-col :span="3">
        <el-card style="height:60vh;max-height: 60vh;overflow-y: scroll">
          <el-input v-model="filterText" placeholder="输入关键字搜索"/>
          <el-tree
            ref="typeTree"
            :data="typeList"
            :props="defaultProps"
            show-checkbox
            :filter-node-method="filterNode"
            @check-change="handleCheckChange"
          />
        </el-card>
      </el-col>
      <el-col :span="13">
        <el-card style="height:60vh;max-height: 60vh;overflow-y: scroll">
          <el-input v-model="searchGoods" placeholder="输入关键字搜索"/>
          <el-table
            v-if="isShowTable"
            ref="leftTable"
            stripe
            border
            :data="goodsList"
            size="small"
            height="500"
            style="width: 100%;"
            highlight-current-row="highlight-current-row"
            @header-dragend="changeColWidth"
            @contextmenu.native="leftShowMenu"
            @sort-change="sortTab"
            @selection-change="changeLeftSelect"
          >
            <el-table-column type="selection" width="55"/>
            <el-table-column type="index" width="55" label="序号"/>
            <el-table-column
              v-for="(item, index) in leftList"
              v-if="item.visible"
              :key="`col_${index}`"
              :prop="item.prop"
              :label="columnLabel(item)"
              :width="item.width + 'px'"
              :data-porp="item.prop"
              :sortable="item.sortable?'custom':false"
              :sort-orders="['descending', 'ascending', null]"
              sort-change="sort"
            >
              <!-- 自定义渲染模版 -->
              <template slot-scope="scope">
                <!-- 当列key为 sort 时，渲染一个手柄icon -->
                <template v-if="item.prop =='sort'">
                  <div class="handle_move">
                    <i :class="scope.row['sort']"/>
                  </div>
                </template>
                <template v-else>
                  <span v-if="item.type == 1" style="margin-left: 10px">{{ scope.row[`${item.prop}`] }}</span>
                  <span v-if="item.type == 2" style="margin-left: 10px">{{
                      parseTime(scope.row[`${item.prop}`])
                    }}</span>
                  <span v-if="item.type == 3" style="margin-left: 10px">{{
                      getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`)
                    }}</span>
                  <span v-if="item.type == 4" style="margin-left: 10px">
                    <span v-if="item.prop === 'mainUnitName'">
                      {{ scope.row.boxUnitName }}/{{ scope.row.mainUnitName }}
                    </span>
                    <span v-if="item.prop === 'usableNum'">
                      {{ computedNum(scope.row) }}
                    </span>

                  </span>
                </template>
              </template>
            </el-table-column>

            <!--            <el-table-column prop="goodsCode" label="编码" />-->
            <!--            <el-table-column prop="goodsName" label="名称" />-->
            <!--            <el-table-column  prop="barcode" label="条形码"/>-->
            <!--            <el-table-column prop="mainUnitName" label="单位" >-->
            <!--              <template slot-scope="scope">-->
            <!--                {{scope.row.boxUnitName}}/{{scope.row.mainUnitName}}-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column prop="boxUnitCount" label="换算率" />-->
            <!--            <el-table-column  prop="usableNum" label="可用量"/>-->
            <!--            <el-table-column  prop="usableNum" label="可用辅数量">-->
            <!--              <template slot-scope="scope">-->
            <!--                {{ computedNum(scope.row) }}-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column  prop="taxPrice" label="单价"/>-->
            <!--            <el-table-column  prop="taxBoxPrice" label="箱价"/>-->
          </el-table>
          <el-pagination
            :current-page.sync="page.page"
            :page-sizes="[10,20,50, 100]"
            :page-size="page.size"
            layout="sizes, prev, pager, next"
            :total="page.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
      <el-col :span="1">
        <div style="height:60vh;max-height: 60vh;display: flex;flex-direction: column;justify-content: center">
          <el-button type="primary" plain @click="addRight">添加-></el-button>
          <br>
          <el-button style="margin-top: 20px" type="danger" plain @click="addLeft"><-删除</el-button>
        </div>

      </el-col>
      <el-col :span="7">
        <el-card style="height:60vh;max-height: 60vh;overflow-y: scroll">
          <el-table
            v-if="isShowTable"
            ref="rightTable"
            height="500"
            stripe
            border
            :data="resultGoods"
            size="small"
            style="width: 100%;"
            @contextmenu.native="rightShowMenu"
            @header-dragend="changeColWidth01"
            @selection-change="changeResultGoodsSelect"
          >
            <el-table-column type="selection" width="55"/>
            <el-table-column type="index" width="55" label="序号"/>

            <el-table-column
              v-for="(item, index) in rightList"
              v-if="item.visible"
              :key="`col_${index}`"
              :prop="item.prop"
              :label="columnLabel(item)"
              :width="item.width + 'px'"
              :data-porp="item.prop"
            >
              <!-- 自定义渲染模版 -->
              <template slot-scope="scope">
                <!-- 当列key为 sort 时，渲染一个手柄icon -->
                <template v-if="item.prop =='sort'">
                  <div class="handle_move">
                    <i :class="scope.row['sort']"/>
                  </div>
                </template>
                <template v-else>
                  <span v-if="item.type == 1" style="margin-left: 10px">{{ scope.row[`${item.prop}`] }}</span>
                  <span v-else-if="item.type == 2" style="margin-left: 10px">{{
                      parseTime(scope.row[`${item.prop}`])
                    }}</span>
                  <span v-else-if="item.type == 3" style="margin-left: 10px">{{
                      getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`)
                    }}</span>
                  <span v-else-if="item.type == 4" style="margin-left: 10px">
                    <span v-if="item.prop === 'secondUnitName'">
                      <el-input
                        v-model="scope.row.boxNum"
                        placeholder=""
                        style="width:45%"
                        @input="computeGoodsCount(scope.row,1)"
                      >
                        <template slot="append"> {{ scope.row.boxUnitName }}</template>
                      </el-input>
                      <el-input
                        v-model="scope.row.mainNum"
                        placeholder=""
                        style="width:45%"
                        @input="computeGoodsCount(scope.row,2)"
                      >
                        <template slot="append"> {{ scope.row.mainUnitName }}</template>
                      </el-input>
                    </span>
                    <span v-else-if="item.prop === 'secondUnitCount'">
                      <el-input
                        v-model="scope.row.goodsCount"
                        placeholder="请输入内容"
                        @input="couputedGoodsUnitCount(scope.row)"
                      />
                    </span>
                  </span>
                </template>
              </template>
            </el-table-column>

            <!--            <el-table-column prop="goodsCode" label="编码" />-->
            <!--            <el-table-column prop="goodsName" label="名称" />-->
            <!--            <el-table-column  prop="barcode" label="条形码"/>-->
            <!--            <el-table-column prop="goodsBrandName" label="商品品牌" />-->
            <!--            <el-table-column prop="goodsTagName" label="商品分类" />-->
            <!--            &lt;!&ndash;            <el-table-column prop="firstUnitName" label="可用量"/>&ndash;&gt;-->
            <!--            &lt;!&ndash;            <el-table-column prop="firstUnitCount" label="可用辅数量"/>&ndash;&gt;-->
            <!--            <el-table-column prop="secondUnitName" label="辅数量" width="400">-->
            <!--              <template slot-scope="scope">-->
            <!--                <el-input-->
            <!--                  v-model="scope.row.boxNum"-->
            <!--                  placeholder=""-->
            <!--                  style="width:45%"-->
            <!--                  @input="computeGoodsCount(scope.row,1)"-->
            <!--                >-->
            <!--                  <template slot="append"> {{ scope.row.boxUnitName }}</template>-->
            <!--                </el-input>-->
            <!--                <el-input-->
            <!--                  v-model="scope.row.mainNum"-->
            <!--                  placeholder=""-->
            <!--                  style="width:45%"-->
            <!--                  @input="computeGoodsCount(scope.row,2)"-->
            <!--                >-->
            <!--                  <template slot="append"> {{ scope.row.mainUnitName }}</template>-->
            <!--                </el-input>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column prop="secondUnitCount" label="数量">-->
            <!--              <template slot-scope="scope">-->
            <!--                <el-input-->
            <!--                  v-model="scope.row.goodsCount"-->
            <!--                  placeholder="请输入内容"-->
            <!--                  @input="couputedGoodsUnitCount(scope.row)"-->
            <!--                />-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column  prop="taxPrice" label="单价"/>-->
            <!--            <el-table-column  prop="taxBoxPrice" label="箱价"/>-->
            <!--            &lt;!&ndash;            <el-table-column prop="goodsMoney" label="单价"/>&ndash;&gt;-->
            <!--            <el-table-column prop="noTaxAmount" label="未税金额" />-->
            <!--            <el-table-column prop="taxAmount" label="含税金额" />-->
            <!--            <el-table-column prop="fCustomerName" label="折扣率"/>-->
            <!--            <el-table-column prop="taxRate" label="详细可用量"/>-->
            <!--            <el-table-column prop="helpSign" label="助记符"/>-->
          </el-table>
        </el-card>
      </el-col>

    </el-row>

    <div class="cu-footer">
      <el-button type="text" @click="closedDialog()">取消</el-button>
      <el-button type="primary" @click="submitCU">确认</el-button>
    </div>
  </div>
</template>

<script>
import {getTypeList} from '@/api/erp/basGoodsType'
import {getGoods} from '@/api/erp/basGoods'
import {selectGoods} from '@/utils/key'
import Sortable from 'sortablejs'
import jTableColumnConfig from '@/components/jTableColumnConfig/jTableColumnConfig'
import pagination from '@crud/Pagination'
import {
  initData
} from '@/api/data'

export default {
  name: 'AddBatch',
  // eslint-disable-next-line vue/no-unused-components
  components: {jTableColumnConfig, pagination},
  mixins: [selectGoods],
  sort: ['id,desc'],
  props: {
    showAddBatchDialog: {
      type: Boolean,
      default: true
    }, params: {
      // 销售单类型
      type: Object,
      default: {}
    },
    saleType: {
      //换货类型
      type: Number,
      default: 0
    },
    type: {
      //订单类型
      type: Number,
      default: 0
    },
    list: Array// 已经选择的数据
  },
  data() {
    return {
      query: {},
      time: 50,
      data: [],
      cateList: [],
      loading: true,
      sort: {},
      emptyList:[2,3,4,5,7],
      typeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      isShowTable: true,
      leftTableConfigShow: false,
      rightTableConfigShow: false,
      filterText: '',
      keyword: '',
      searchGoods: '',
      page: {
        page: 1,
        size: 50,
        total: 0
      },
      goodsList: [],
      selectTypes: [], // 选中的分类
      resultGoods: [], // 右边的数据民
      leftGoodsSelect: [],
      resultGoodsSelect: [],
      leftContextMenuData: {
        menuName: 'leftTable',
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [{
          fnHandler: 'tableConfig', // 绑定事件
          icoName: 'el-icon-setting', // icon图标
          btnName: '表格设置' // 菜单名称
        }]
      },
      rightContextMenuData: {
        menuName: 'rightTable',
        axis: {
          x: null,
          y: null
        },
        // 菜单选项
        menulists: [{
          fnHandler: 'tableConfig', // 绑定事件
          icoName: 'el-icon-setting', // icon图标
          btnName: '表格设置' // 菜单名称
        }]
      },
      leftList: [{
        'dictionary': '',
        'label': '商品编码',
        'prop': 'goodsCode',
        'showName': '',
        'type': '1',
        'visible': false,
        'width': 100
      },
        {
          'dictionary': '',
          'label': '商品名称',
          'prop': 'goodsName',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 300
        },
        {
          'dictionary': '',
          'label': '条形码',
          'prop': 'barcode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 150
        },
        {
          'dictionary': '',
          'label': '单位',
          'prop': 'mainUnitName',
          'showName': '',
          'type': '4',
          'visible': false,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '换算率',
          'prop': 'boxUnitCount',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '可用量',
          'prop': 'usableNum',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '可用辅数量',
          'prop': 'usableNum',
          'showName': '',
          'type': '4',
          'visible': true,
          'width': 90
        },
        {
          'dictionary': '',
          'label': '箱条码',
          'prop': 'boxBarcode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '规格',
          'prop': 'model',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '单价',
          'prop': 'taxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '箱价',
          'prop': 'taxBoxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        }
      ],
      rightList: [{
        'dictionary': '',
        'label': '商品编码',
        'prop': 'goodsCode',
        'showName': '',
        'type': '1',
        'visible': false,
        'width': 100
      },
        {
          'dictionary': '',
          'label': '商品名称',
          'prop': 'goodsName',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 400
        },
        {
          'dictionary': '',
          'label': '条形码',
          'prop': 'barcode',
          'showName': '',
          'type': '1',
          'visible': false,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '商品品牌',
          'prop': 'goodsBrandName',
          'showName': '',
          'type': '1',
          'visible': false,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '商品分类',
          'prop': 'goodsTagName',
          'showName': '',
          'type': '1',
          'visible': false,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '辅数量',
          'prop': 'secondUnitName',
          'showName': '',
          'type': '4',
          'visible': false,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '数量',
          'prop': 'secondUnitCount',
          'showName': '',
          'type': '4',
          'visible': false,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '单价',
          'prop': 'taxPrice',
          'showName': '',
          'type': '1',
          'visible': false,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '箱价',
          'prop': 'taxBoxPrice',
          'showName': '',
          'type': '1',
          'visible': false,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '未税金额',
          'prop': 'noTaxAmount',
          'showName': '',
          'type': '1',
          'visible': false,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '含税金额',
          'prop': 'taxAmount',
          'showName': '',
          'type': '1',
          'visible': false,
          'width': 100
        }
      ]
    }
  },
  watch: {
    searchGoods: function (n) {
      this.keyword = n
      console.log('======')
      this.getGoodsList()
    },
    filterText(val) {
      this.$refs.typeTree.filter(val)
    }

  },
  mounted() {
    this.getList()
  },
  created() {
    this.getTypeList()
    this.resultGoods = JSON.parse(JSON.stringify(this.list))
    const leftList = JSON.parse(localStorage.getItem('leftList'))
    const rightList = JSON.parse(localStorage.getItem('rightList'))
    this.leftList = leftList || this.leftList
    this.rightList = rightList || this.rightList
  },
  methods: {
    getQueryParame: function () {
      return {
        page: this.page.page,
        size: this.page.size,
        sort: this.sort,
        ...this.query,
        ...this.params
      }
    },
    beforeInit() {
      return true
    },
    toQuery() {
      this.page.page = 0
      this.getGoodsList()
    },
    sortTab(row, before) {
      console.log(1111111111)
      if (row.column.order) {
        this.query.sort = `${row.column.property},${row.column.order === 'ascending' ? 'asc' : 'desc'}`
        // this.sort[row.column.property] = row.column.order === 'ascending'?'asc':'desc'
        console.log(this.query.sort)
      } else {
        try {
          this.query.sort = null
          // Reflect.deleteProperty(this.sort,row.column.property)
        } catch (e) {
          console.err(e)
        }
      }
      // let str = ''
      // for(let key in this.sort){
      //   str += `${key},${this.sort[key]}|`
      // }
      // this.query.sort = str.slice(0,-1)

      // console.log(str.slice(0,-1))
      this.toQuery()
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    async getList() {
      this.leftInitSortable()
      this.rightInitSortable()
    },
    leftShowMenu() {
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      // Get the current location
      this.leftContextMenuData.axis = {
        x, y
      }
    },
    rightShowMenu() {
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      // Get the current location
      this.rightContextMenuData.axis = {
        x, y
      }
    },
    handleSizeChange(val) {
      this.page.size = val
      this.getGoodsList()
    },
    handleCurrentChange(val) {
      this.page.page = val
      this.getGoodsList()
    },
    tableConfig() {
      this.tableConfigShow = true
    },
    leftTableConfig() {
      this.leftTableConfigShow = true
    },
    rightTableConfig() {
      this.rightTableConfigShow = true
    },
    // 动态计算商品数量
    computeGoodsCount(row, index) {
      console.log(row)
      row.goodsCount = row.boxUnitCount * row.boxNum + row.mainUnitCount * row.mainNum
      this.computedMoney(row)
    },
    computedNum(goods) {
      const boxCount = parseInt(goods.usableNum / Number(goods.boxUnitCount))
      const mainCount = goods.usableNum % Number(goods.boxUnitCount)
      return `${boxCount}${goods.boxUnitName}${mainCount}${goods.mainUnitName}`
    },
    changeColWidth(nw, ow, col, evt) {
      const list = this.leftList
      list.map((res, i) => {
        if (res.label === col.label) {
          this.leftList[i].width = nw
        }
      })
      localStorage.setItem('leftList', JSON.stringify(this.leftList))
      console.log('缓存设置成功')
    },
    changeColWidth01(nw, ow, col, evt) {
      const list = this.rightList
      list.map((res, i) => {
        if (res.label === col.label) {
          this.rightList[i].width = nw
        }
      })
      localStorage.setItem('rightList', JSON.stringify(this.rightList))
      console.log('right缓存设置成功')
    },
    couputedGoodsUnitCount(row) {
      // 判断是否满足最小销售单位和退货单位
      if (row.minSaleUnitCount && this.type == 'SALE' && row.minSaleUnitCount > 0) {
        if (row.goodsCount % row.mainNum != 0) {
          // 不满足
          this.$message.error('请输入最小销售单位' + row.minSaleUnitCount + '整数倍的数量')
          return false
        }
      }
      if (row.minReturnUnitCount && this.type == 'SALE_RETURN' && row.minReturnUnitCount > 0) {
        if (row.goodsCount % row.mainNum != 0) {
          // 不满足
          this.$message.error('请输入最小退货单位' + row.minReturnUnitCount + '整数倍的数量')
          return false
        }
      }

      if (row.boxUnitCount > 0) {
        row.boxNum = Math.floor(row.goodsCount / row.boxUnitCount)
      }
      if (row.mainUnitCount > 0) {
        row.mainNum = Math.floor((row.goodsCount - row.boxUnitCount * row.boxNum) / row.mainUnitCount)
      }
      this.computedMoney(row)
    },
    computedMoney(row) {
      console.log(row)
      // 计算价格
      row.noTaxAmount = row.noTaxBoxPrice * row.boxNum + row.noTaxPrice * row.mainNum
      row.taxAmount = row.taxBoxPrice * row.boxNum + row.taxPrice * row.mainNum
      this.$forceUpdate()
    },
    changeLeftSelect(sel) {
      this.leftGoodsSelect = sel
    },
    changeResultGoodsSelect(sel) {
      this.resultGoodsSelect = sel
    },
    handleCheckChange() {
      console.log(123)
      // 传递给 data 属性的数组中该节点所对应的对象、节点本身是否被选中、节点的子树中是否有被选中的节点
      // rows为选中的数据
      const rows = this.$refs.typeTree.getCheckedNodes()
      if (rows.length == 0) {
        return false
      }
      this.selectTypes = rows.map(r => r.id)
      this.getGoodsList()
    },
    columnLabel(obj) {
      if (obj.showName) {
        return obj.showName
      }
      obj.showName = obj.label
      return obj.showName
    },
    getTypeList() {
      let obj = {page: 0, size: 999}
      if (this.filterText) {
        obj = Object.assign(obj, {keyword: this.filterText})
      }
      getTypeList(obj).then(res => {
        this.typeList = res
      })
    },
    getGoodsList() {

      let obj = Object.assign(this.params, {...this.page}, this.query)
      if (this.searchGoods) {
        obj = Object.assign(obj, {keyword: this.searchGoods})
      }

      obj = Object.assign(obj, {goodsTypeIds: this.selectTypes.toString()})

      const arr = this.goodsList.map(good => {
        return good.goodsId
      })
      const searchGoods = this.searchGoods
      getGoods(obj).then(res => {
        console.log(this.searchGoods)
        console.log(searchGoods)
        if (this.searchGoods !== searchGoods) {
          return
        }
        this.goodsList = []
        for (const obj of res.content) {
          if (arr.indexOf(obj.goodsId) < 0) {
            // 给这个goods 添加自定义属性
            obj['boxNum'] = 0
            obj['mainNum'] = 0
            obj['goodsCount'] = 0

            this.goodsList.push(obj)
          }
        }
        this.goodsList = res.content
        this.page.total = res.totalElements
      })
    },
    closedDialog() {
      this.$emit('update:showAddBatchDialog', false)
    },
    addLeft() {
      // 只在右边删除
      const resultIds = this.resultGoods.map(result => result.id)
      this.resultGoodsSelect.forEach(result => {
        const _in = resultIds.indexOf(result.id)
        if (_in > -1) {
          this.resultGoods.splice(_in, 1)
        }
      })
    },
    addRight() {
      // 添加到右边，防止重复添加
      const resultIds = this.resultGoods.map(result => result.goodsId)
      console.log(this.leftGoodsSelect)
      this.leftGoodsSelect.forEach(left => {
        if (resultIds.indexOf(left.goodsId) < 0) {
          this.resultGoods.push(Object.assign({},left))
        }
      })
      this.$forceUpdate()
    },
    submitCU() {
      console.log(this.resultGoods)
      // 判断一下每个商品的数量是不是最小的数量的倍数
      for (const obj of this.resultGoods) {
        if (!this.checkMinUnitCount(obj)) {
          return false
        }
      }
      this.closedDialog()
      if (this.emptyList.includes(this.saleType) && this.type === 1) {
        this.resultGoods.forEach(item => {
          item.taxPrice = 0
          item.taxBoxPrice = 0
          item.billTaxPrice = 0
          item.billTaxBoxPrice = 0
        })
      }
      this.$emit('change', this.resultGoods)
    },
    // 判断是否满足最小单位
    checkMinUnitCount(row) {
      if (this.type == 'SALE' && row.minSaleUnitCount > 0) {
        if (row.goodsCount % row.mainNum != 0) {
          // 不满足
          this.$message.error('请修改商品【' + row.goodsName + '】的数量为最小销售单位【' + row.minSaleUnitCount + '】整数倍')
          return false
        }
      }
      if (this.type == 'SALE_RETURN' && row.minReturnUnitCount > 0) {
        if (row.goodsCount % row.mainNum != 0) {
          // 不满足
          this.$message.error('请修改商品【' + row.goodsName + '】的数量为最小销售单位【' + row.minReturnUnitCount + '】整数倍')
          return false
        }
      }
      return true
    },

    leftTabSave() {
      this.leftTableConfigShow = false
      this.toUpdateHeader()
      this.handleCancelSort()
    },
    rightTabSave() {
      this.rightTableConfigShow = false
      this.toUpdateHeader()
      this.handleCancelSort()
    },
    pit() {
      this.toUpdateHeader()
      this.handleCancelSort()
    },
    toUpdateHeader() {
      localStorage.setItem('leftList', JSON.stringify(this.leftList))
      localStorage.setItem('rightList', JSON.stringify(this.rightList))
      console.log('设置缓存成功')
    },
    handleCancelSort() {
      // 使table先隐藏，再显示，table将恢复拖拽之前的样式
      this.isShowTable = false
      setTimeout(() => {
        this.isShowTable = true
        // 必须延时，否则重新初始化的sortable无法拖拽
        setTimeout(() => {
          this.leftInitSortable()
          this.rightInitSortable()
        }, 500)
      }, 100)
    },
    leftInitSortable() {
      const th = this
      const el = this.$refs.leftTable.$el.querySelector('.el-table__header-wrapper thead tr')
      // 创建拖拽对象
      new Sortable(el, {
        onEnd(evt) {
          const {newIndex, oldIndex, item} = evt
          const noSort = [0, 1]
          if (noSort.includes(newIndex) || noSort.includes(oldIndex)) {
            return
          }
          // 获取原来title的name
          const oldtitle = item.children[0].innerHTML
          let thOldIndex = -1
          // 根据name获取所在的索引
          for (let i = 0; i < th.leftList.length; i++) {
            if (th.leftList[i].showName === oldtitle) {
              thOldIndex = i
              break
            }
          }
          // 获取隐藏后的数组
          const list = th.leftList.filter(item => item.visible === true)
          // 获取新位置所在的name值
          const newtitle = list[newIndex - 2].showName
          // 根据name获取所在的索引
          let thNewIndex = -1
          for (let i = 0; i < th.leftList.length; i++) {
            console.log('======')
            console.log(th.leftList[i].showName)
            console.log(newtitle)
            if (th.leftList[i].showName === newtitle) {
              thNewIndex = i
              break
            }
          }
          const temp = th.leftList[thOldIndex]
          if (temp === null || temp === undefined) {
            return
          }
          th.leftList.splice(thOldIndex, 1)
          th.leftList.splice(thNewIndex, 0, temp)
          th.toUpdateHeader()
          th.handleCancelSort()
        }
      })
    },
    leftContextMenuData() {

    },
    contextMenuData() {

    },
    rightInitSortable() {
      const th = this
      const el = this.$refs.rightTable.$el.querySelector('.el-table__header-wrapper thead tr')
      console.log(el)
      // 创建拖拽对象
      new Sortable(el, {
        onEnd(evt) {
          const {newIndex, oldIndex, item} = evt
          const noSort = [0, 1]
          if (noSort.includes(newIndex) || noSort.includes(oldIndex)) {
            return
          }
          // 获取原来title的name
          const oldtitle = item.children[0].innerHTML
          let thOldIndex = -1
          // 根据name获取所在的索引
          for (let i = 0; i < th.rightList.length; i++) {
            if (th.rightList[i].showName === oldtitle) {
              thOldIndex = i
              break
            }
          }
          // 获取隐藏后的数组
          const list = th.rightList.filter(item => item.visible === true)
          // 获取新位置所在的name值
          const newtitle = list[newIndex - 2].showName
          // 根据name获取所在的索引
          let thNewIndex = -1
          for (let i = 0; i < th.rightList.length; i++) {
            if (th.rightList[i].showName === newtitle) {
              thNewIndex = i
              break
            }
          }

          const temp = th.rightList[thOldIndex]
          if (temp === null || temp === undefined) {
            return
          }
          th.rightList.splice(thOldIndex, 1)
          th.rightList.splice(thNewIndex, 0, temp)
          th.toUpdateHeader()
          th.handleCancelSort()
        }
      })
    }
  }
}
</script>

<style scoped>
.cu-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-top: 20px;
}
</style>
